<template>
  <div class="inventory-page">
    <!-- 页面标题 -->
    <h2 class="page-title mb-4">库存查询</h2>
    
    <!-- 时间筛选标签页 -->
    <el-tabs v-model="activeTime" class="mb-4" type="card">
      <el-tab-pane label="今日" name="today" @click="handleTime('today')">
        <div class="text-center text-gray-500">今天{{ new Date().toLocaleDateString() }}</div>
      </el-tab-pane>
      <el-tab-pane label="昨日" name="yesterday" @click="handleTime('yesterday')">
        <div class="text-center text-gray-500">昨天{{ formatYesterday() }}</div>
      </el-tab-pane>
      <el-tab-pane label="本周" name="thisWeek" @click="handleTime('thisWeek')">
        <div class="text-center text-gray-500">第{{ getCurrentWeek() }}周数据</div>
      </el-tab-pane>
      <el-tab-pane label="上周" name="lastWeek" @click="handleTime('lastWeek')">
        <div class="text-center text-gray-500">第{{ getCurrentWeek() - 1 }}周数据</div>
      </el-tab-pane>
      <el-tab-pane label="本月" name="thisMonth" @click="handleTime('thisMonth')">
        <div class="text-center text-gray-500">{{ getCurrentMonth() }}月数据</div>
      </el-tab-pane>
      <el-tab-pane label="上月" name="lastMonth" @click="handleTime('lastMonth')">
        <div class="text-center text-gray-500">{{ getLastMonth() }}月数据</div>
      </el-tab-pane>
      <el-tab-pane label="最近半年" name="halfYear" @click="handleTime('halfYear')">
        <div class="text-center text-gray-500">最近6个月数据</div>
      </el-tab-pane>
      <el-tab-pane label="最近一年" name="oneYear" @click="handleTime('oneYear')">
        <div class="text-center text-gray-500">最近12个月数据</div>
      </el-tab-pane>
      <el-tab-pane label="自定义时间" name="custom" @click="handleTime('custom')">
        <div class="text-center text-gray-500">选择日期范围</div>
      </el-tab-pane>
    </el-tabs>

    <!-- 查询表单 -->
    <el-card shadow="hover" class="mb-4">
      <el-form :model="searchForm" inline class="demo-form-inline">
        <el-form-item label="货品">
          <el-input v-model="searchForm.goodsName" placeholder="请输入货品名称/编号" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="货品类型">
          <el-select v-model="searchForm.goodsType" placeholder="请选择">
            <el-option label="全部" value="" />
            <el-option label="电子产品" value="电子产品" />
            <el-option label="家电" value="家电" />
            <el-option label="服装" value="服装" />
            <el-option label="食品" value="食品" />
            <el-option label="化妆品" value="化妆品" />
            <el-option label="鞋类" value="鞋类" />
            <el-option label="配饰" value="配饰" />
            <el-option label="玩具" value="玩具" />
            <el-option label="书籍" value="书籍" />
            <el-option label="运动器材" value="运动器材" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位">
          <el-select v-model="searchForm.unit" placeholder="请选择">
            <el-option label="全部" value="" />
            <el-option label="台" value="台" />
            <el-option label="个" value="个" />
            <el-option label="瓶" value="瓶" />
            <el-option label="盒" value="盒" />
            <el-option label="条" value="条" />
            <el-option label="件" value="件" />
            <el-option label="双" value="双" />
            <el-option label="块" value="块" />
            <el-option label="套" value="套" />
            <el-option label="本" value="本" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-select v-model="searchForm.warehouseName" placeholder="请选择">
            <el-option label="全部" value="" />
            <el-option label="仓库一" value="仓库一" />
            <el-option label="仓库二" value="仓库二" />
            <el-option label="临时仓库" value="临时仓库" />
          </el-select>
        </el-form-item>
        <el-form-item label="货品条码">
          <el-input v-model="searchForm.barcode" placeholder="请输入货品条码" style="width: 180px;" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="searchForm.showDisabled">停用商品</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="searchForm.showZeroStock">零库存商品</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="12" class="mb-4">
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover" class="stat-card bg-gradient-primary">
          <div class="stat-content">
            <div class="stat-value">{{ statistics.stockCount.toLocaleString() }}</div>
            <div class="stat-label">当前库存数量</div>
            <div class="stat-value amount">¥{{ statistics.stockAmount.toLocaleString('zh-CN', {minimumFractionDigits: 2}) }}</div>
            <div class="stat-label">当前库存金额</div>
            <div class="stat-icon"><el-icon><Box /></el-icon></div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover" class="stat-card bg-gradient-success">
          <div class="stat-content">
            <div class="stat-value">+{{ statistics.inStockCount.toLocaleString() }}</div>
            <div class="stat-label">入库数量</div>
            <div class="stat-value text-orange">-{{ statistics.outStockCount.toLocaleString() }}</div>
            <div class="stat-label">出库数量</div>
            <div class="stat-icon"><el-icon><TrendCharts /></el-icon></div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="8">
        <el-card shadow="hover" class="stat-card bg-gradient-warning">
          <div class="stat-content">
            <div class="stat-value">{{ statistics.waitInStock.toLocaleString() }}</div>
            <div class="stat-label">待入库</div>
            <div class="stat-value">{{ statistics.waitOutStock.toLocaleString() }}</div>
            <div class="stat-label">待出库</div>
            <div class="stat-icon"><el-icon><Timer /></el-icon></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <div class="flex mb-4 justify-between items-center">
      <div>
        <el-button type="success" @click="handleExport" icon="DocumentCopy">导出</el-button>
        <el-button type="info" @click="handleRefresh" icon="Refresh">刷新</el-button>
      </div>
      <div class="text-gray-500 text-sm">数据更新时间：{{ lastUpdateTime }}</div>
    </div>

    <!-- 货品表格 -->
    <el-card shadow="hover">
      <div class="table-header mb-4">
        <span class="table-title">库存数据列表</span>
        <span class="data-count">共 {{ pagination.total }} 条记录</span>
      </div>
      <el-table :data="tableData" border style="width: 100%" stripe hover-row-class-name="hover-row">
        <el-table-column prop="index" label="序号" width="80" align="center" />
        <el-table-column prop="goodsCode" label="货品编号" width="120" align="center" />
        <el-table-column prop="goodsName" label="货品名称" width="180">
          <template #default="scope">
            <span class="goods-name">{{ scope.row.goodsName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '启用' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="goodsType" label="货品类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.goodsType)">
              {{ scope.row.goodsType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="spec" label="规格型号" width="120" align="center" />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="barcode" label="条码" width="150" align="center" />
        <el-table-column prop="warehouseName" label="仓库名称" width="120" align="center" />
        <el-table-column prop="locationName" label="库位名称" width="120" align="center" />
        <el-table-column prop="currentStock" label="当前库存" width="120" align="center">
          <template #default="scope">
            <span :class="{ 'stock-low': scope.row.currentStock < 50, 'stock-zero': scope.row.currentStock === 0 }">
              {{ scope.row.currentStock }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="stockAmount" label="库存金额" width="120" align="center">
          <template #default="scope">
            <span class="amount">¥{{ scope.row.stockAmount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleStockFlow(scope.row)" circle>
              <el-icon><Operation /></el-icon>
            </el-button>
            <el-button size="small" @click="handleStockDistribution(scope.row)" circle>
              <el-icon><DataLine /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        class="mt-4"
      />
    </el-card>
  </div>
  
  <!-- 出入库流水对话框 -->
  <el-dialog
    v-model="stockFlowDialogVisible"
    :title="`${selectedGoods?.goodsName || ''} - 出入库流水记录`"
    width="80%"
    destroy-on-close
  >
    <div class="flow-dialog-content">
      <div class="flow-summary mb-4">
        <div class="summary-item">
          <span class="label">货品编号：</span>
          <span class="value">{{ selectedGoods?.goodsCode || '-' }}</span>
        </div>
        <div class="summary-item">
          <span class="label">当前库存：</span>
          <span class="value stock-value">{{ selectedGoods?.currentStock || 0 }} {{ selectedGoods?.unit || '' }}</span>
        </div>
        <div class="summary-item">
          <span class="label">查看时间：</span>
          <span class="value">{{ new Date().toLocaleString() }}</span>
        </div>
      </div>
      
      <el-table :data="stockFlowData" border style="width: 100%" stripe>
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="time" label="时间" width="80" />
        <el-table-column prop="type" label="类型" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.type === '入库' ? 'success' : 'danger'">{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="原因" width="120" />
        <el-table-column prop="quantity" label="数量" width="100">
          <template #default="scope">
            <span :class="scope.row.quantity > 0 ? 'text-green' : 'text-red'">
              {{ scope.row.quantity > 0 ? '+' : '' }}{{ scope.row.quantity }} {{ selectedGoods?.unit || '' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="scope">
            <span class="amount">¥{{ scope.row.unitPrice.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="scope">
            <span class="amount">¥{{ scope.row.amount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="operator" label="操作员" width="100" />
      </el-table>
      
      <div class="mt-4 text-center text-gray-500">
        显示最近50条记录
      </div>
    </div>
  </el-dialog>
  
  <!-- 库存分布对话框 -->
  <el-dialog
    v-model="stockDistributionDialogVisible"
    :title="`${selectedGoods?.goodsName || ''} - 库存分布`"
    width="60%"
    destroy-on-close
  > 
    <div class="distribution-dialog-content">
      <div class="distribution-summary mb-6">
        <div class="summary-item">
          <span class="label">货品编号：</span>
          <span class="value">{{ selectedGoods?.goodsCode || '-' }}</span>
        </div>
        <div class="summary-item">
          <span class="label">总库存：</span>
          <span class="value stock-value">{{ selectedGoods?.currentStock || 0 }} {{ selectedGoods?.unit || '' }}</span>
        </div>
        <div class="summary-item">
          <span class="label">分布仓库数：</span>
          <span class="value">{{ stockDistributionData.length }}</span>
        </div>
      </div>
      
      <div class="warehouse-distribution">
        <div v-for="(warehouse, index) in stockDistributionData" :key="index" class="warehouse-card">
          <div class="warehouse-header">
            <h3>{{ warehouse.warehouse }}</h3>
            <span class="warehouse-stock">{{ warehouse.stock }} {{ selectedGoods?.unit || '' }}</span>
          </div>
          <div class="warehouse-percentage">
            <el-progress :percentage="Number(warehouse.percentage)" :show-text="true" />
          </div>
          
          <div class="locations mt-4">
            <h4 class="locations-title">库位分布：</h4>
            <div class="location-list">
              <div v-for="(location, locIndex) in warehouse.locations" :key="locIndex" class="location-item">
                <div class="location-info">
                  <span class="location-name">{{ location.name }}</span>
                  <span class="location-stock">{{ location.stock }} {{ selectedGoods?.unit || '' }}</span>
                </div>
                <div class="location-percentage">
                  <el-progress :percentage="Number(location.percentage)" :show-text="true" :stroke-width="8" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { Box, TrendCharts, Timer, Operation, DataLine } from '@element-plus/icons-vue';
import { ElLoading, ElMessage, ElDialog, ElTable as ElDialogTable, ElTableColumn as ElDialogTableColumn } from 'element-plus';

// 时间筛选激活状态
const activeTime = ref('today');

// 查询表单数据（硬编码，无API依赖）
const searchForm = reactive({
  goodsName: '',
  goodsType: '',
  unit: '',
  warehouseName: '',
  barcode: '',
  showDisabled: false,
  showZeroStock: false,
});

// 统计数据（根据时间筛选动态变化）
const statistics = reactive({
  stockCount: 1856,
  stockAmount: 1245680.50,
  inStockCount: 324,
  outStockCount: 218,
  waitInStock: 156,
  waitOutStock: 98,
});

// 根据时间筛选更新统计数据
const updateStatisticsByTime = (timeType) => {
  const statsByTime = {
    today: {
      stockCount: 1856,
      stockAmount: 1245680.50,
      inStockCount: 45,
      outStockCount: 23,
      waitInStock: 156,
      waitOutStock: 98,
    },
    yesterday: {
      stockCount: 1834,
      stockAmount: 1234560.75,
      inStockCount: 38,
      outStockCount: 29,
      waitInStock: 142,
      waitOutStock: 87,
    },
    thisWeek: {
      stockCount: 1856,
      stockAmount: 1245680.50,
      inStockCount: 216,
      outStockCount: 158,
      waitInStock: 156,
      waitOutStock: 98,
    },
    lastWeek: {
      stockCount: 1802,
      stockAmount: 1210345.20,
      inStockCount: 198,
      outStockCount: 142,
      waitInStock: 134,
      waitOutStock: 86,
    },
    thisMonth: {
      stockCount: 1856,
      stockAmount: 1245680.50,
      inStockCount: 875,
      outStockCount: 642,
      waitInStock: 156,
      waitOutStock: 98,
    },
    lastMonth: {
      stockCount: 1756,
      stockAmount: 1189765.30,
      inStockCount: 765,
      outStockCount: 589,
      waitInStock: 124,
      waitOutStock: 89,
    },
    halfYear: {
      stockCount: 1856,
      stockAmount: 1245680.50,
      inStockCount: 4321,
      outStockCount: 3567,
      waitInStock: 156,
      waitOutStock: 98,
    },
    oneYear: {
      stockCount: 1856,
      stockAmount: 1245680.50,
      inStockCount: 8976,
      outStockCount: 7234,
      waitInStock: 156,
      waitOutStock: 98,
    },
    custom: {
      stockCount: 1856,
      stockAmount: 1245680.50,
      inStockCount: 324,
      outStockCount: 218,
      waitInStock: 156,
      waitOutStock: 98,
    }
  };
  
  const newStats = statsByTime[timeType] || statsByTime.today;
  Object.assign(statistics, newStats);
};

// 最后更新时间
const lastUpdateTime = computed(() => {
  return new Date().toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
});

// 完整的库存数据
const fullStockData = [
  {
    index: 1,
    goodsCode: 'HPDH6773',
    goodsName: 'Apple iPhone 15 Pro Max',
    status: '启用',
    goodsType: '电子产品',
    spec: '256GB/钛金属原色',
    unit: '台',
    barcode: 'IP1520240301-001',
    warehouseName: '仓库一',
    locationName: 'A区-01-01',
    currentStock: 128,
    stockAmount: 1280000.00,
  },
  {
    index: 2,
    goodsCode: 'HPDH9200',
    goodsName: '三星QLED 8K智能电视',
    status: '启用',
    goodsType: '家电',
    spec: '85英寸/QN900C',
    unit: '台',
    barcode: 'SAM20240302-001',
    warehouseName: '仓库二',
    locationName: 'B区-02-03',
    currentStock: 15,
    stockAmount: 450000.00,
  },
  {
    index: 3,
    goodsCode: 'HPDH5675',
    goodsName: '德龙全自动咖啡机',
    status: '启用',
    goodsType: '家电',
    spec: 'ECAM 650.85.MS',
    unit: '台',
    barcode: 'DEL20240303-001',
    warehouseName: '仓库一',
    locationName: 'C区-03-05',
    currentStock: 42,
    stockAmount: 126000.00,
  },
  {
    index: 4,
    goodsCode: 'HPDN3078',
    goodsName: '格力中央空调',
    status: '启用',
    goodsType: '家电',
    spec: 'GMV-H120WL/C1',
    unit: '套',
    barcode: 'GLE20240304-001',
    warehouseName: '仓库一',
    locationName: 'D区-01-02',
    currentStock: 8,
    stockAmount: 400000.00,
  },
  {
    index: 5,
    goodsCode: 'HPDH8551',
    goodsName: '戴森空气净化器',
    status: '启用',
    goodsType: '家电',
    spec: 'TP09/黑金版',
    unit: '台',
    barcode: 'DY20240305-001',
    warehouseName: '仓库二',
    locationName: 'E区-02-04',
    currentStock: 78,
    stockAmount: 234000.00,
  },
  {
    index: 6,
    goodsCode: 'HPDH4022',
    goodsName: '小米智能家居套装',
    status: '停用',
    goodsType: '电子产品',
    spec: 'Pro 12件套',
    unit: '套',
    barcode: 'XIA20231201-001',
    warehouseName: '仓库一',
    locationName: 'F区-03-01',
    currentStock: 15,
    stockAmount: 45000.00,
  },
  {
    index: 7,
    goodsCode: 'HPDN6220',
    goodsName: '劳力士潜航者系列腕表',
    status: '启用',
    goodsType: '配饰',
    spec: '126610LN/黑色表盘',
    unit: '块',
    barcode: 'ROL20240307-001',
    warehouseName: '临时仓库',
    locationName: 'VIP-01-01',
    currentStock: 3,
    stockAmount: 450000.00,
  },
  {
    index: 8,
    goodsCode: 'HPDH5085',
    goodsName: '派克IM系列钢笔套装',
    status: '启用',
    goodsType: '文具',
    spec: '金夹宝珠笔套装',
    unit: '盒',
    barcode: 'PKE20240308-001',
    warehouseName: '仓库二',
    locationName: 'G区-01-03',
    currentStock: 256,
    stockAmount: 128000.00,
  },
  {
    index: 9,
    goodsCode: 'HPDH7785',
    goodsName: '双立人厨具套装',
    status: '启用',
    goodsType: '家居用品',
    spec: 'TWIN Chef 32件套',
    unit: '套',
    barcode: 'ZWL20240309-001',
    warehouseName: '仓库一',
    locationName: 'H区-02-01',
    currentStock: 28,
    stockAmount: 112000.00,
  },
  {
    index: 10,
    goodsCode: 'HPDN5331',
    goodsName: 'Nike Air Jordan 1',
    status: '启用',
    goodsType: '鞋类',
    spec: '芝加哥/42码',
    unit: '双',
    barcode: 'NKJ20240310-001',
    warehouseName: '仓库一',
    locationName: 'I区-01-01',
    currentStock: 0,
    stockAmount: 0.00,
  },
  // 增加更多数据以支持分页
  {
    index: 11,
    goodsCode: 'HPDH8899',
    goodsName: '索尼PlayStation 5',
    status: '启用',
    goodsType: '电子产品',
    spec: '光驱版/白色',
    unit: '台',
    barcode: 'SON20240311-001',
    warehouseName: '仓库一',
    locationName: 'A区-02-03',
    currentStock: 67,
    stockAmount: 201000.00,
  },
  {
    index: 12,
    goodsCode: 'HPDH7766',
    goodsName: '佳能EOS R5相机',
    status: '启用',
    goodsType: '电子产品',
    spec: '全画幅/4500万像素',
    unit: '台',
    barcode: 'CAN20240312-001',
    warehouseName: '仓库二',
    locationName: 'B区-03-01',
    currentStock: 12,
    stockAmount: 288000.00,
  },
  {
    index: 13,
    goodsCode: 'HPDH6655',
    goodsName: '特斯拉Model 3车模',
    status: '启用',
    goodsType: '玩具',
    spec: '1:18/白色',
    unit: '盒',
    barcode: 'TES20240313-001',
    warehouseName: '仓库一',
    locationName: 'C区-02-04',
    currentStock: 156,
    stockAmount: 46800.00,
  },
  {
    index: 14,
    goodsCode: 'HPDH5544',
    goodsName: '乐高星球大战千年隼',
    status: '启用',
    goodsType: '玩具',
    spec: '75192/7541片',
    unit: '盒',
    barcode: 'LEG20240314-001',
    warehouseName: '仓库二',
    locationName: 'D区-03-02',
    currentStock: 7,
    stockAmount: 105000.00,
  },
  {
    index: 15,
    goodsCode: 'HPDH4433',
    goodsName: '兰蔻小黑瓶精华液',
    status: '启用',
    goodsType: '化妆品',
    spec: '50ml',
    unit: '瓶',
    barcode: 'LAN20240315-001',
    warehouseName: '仓库一',
    locationName: 'E区-01-03',
    currentStock: 45,
    stockAmount: 45000.00,
  },
  {
    index: 16,
    goodsCode: 'HPDH3322',
    goodsName: '星巴克咖啡豆',
    status: '启用',
    goodsType: '食品',
    spec: '500g/哥伦比亚风味',
    unit: '袋',
    barcode: 'STA20240316-001',
    warehouseName: '仓库二',
    locationName: 'F区-02-01',
    currentStock: 203,
    stockAmount: 60900.00,
  },
  {
    index: 17,
    goodsCode: 'HPDH2211',
    goodsName: '阿迪达斯Ultraboost跑鞋',
    status: '启用',
    goodsType: '鞋类',
    spec: '42码/灰色',
    unit: '双',
    barcode: 'ADI20240317-001',
    warehouseName: '仓库一',
    locationName: 'G区-03-05',
    currentStock: 34,
    stockAmount: 27200.00,
  },
  {
    index: 18,
    goodsCode: 'HPDH1100',
    goodsName: 'Nike运动T恤',
    status: '停用',
    goodsType: '服装',
    spec: 'XL/黑色',
    unit: '件',
    barcode: 'NIK20240318-001',
    warehouseName: '仓库二',
    locationName: 'H区-01-02',
    currentStock: 0,
    stockAmount: 0.00,
  },
  {
    index: 19,
    goodsCode: 'HPDH9988',
    goodsName: '羽毛球拍套装',
    status: '启用',
    goodsType: '运动器材',
    spec: '尤尼克斯/双拍',
    unit: '套',
    barcode: 'BAD20240319-001',
    warehouseName: '仓库一',
    locationName: 'I区-02-04',
    currentStock: 89,
    stockAmount: 26700.00,
  },
  {
    index: 20,
    goodsCode: 'HPDH8877',
    goodsName: '《哈利波特》全集',
    status: '启用',
    goodsType: '书籍',
    spec: '精装版/7册',
    unit: '套',
    barcode: 'HAR20240320-001',
    warehouseName: '仓库二',
    locationName: 'A区-03-01',
    currentStock: 123,
    stockAmount: 98400.00,
  },
  // 再增加更多数据
  {
    index: 21,
    goodsCode: 'HPDH7766',
    goodsName: '华为Mate 60 Pro',
    status: '启用',
    goodsType: '电子产品',
    spec: '512GB/玄黑',
    unit: '台',
    barcode: 'HUA20240321-001',
    warehouseName: '仓库一',
    locationName: 'B区-01-03',
    currentStock: 89,
    stockAmount: 623000.00,
  },
  {
    index: 22,
    goodsCode: 'HPDH6655',
    goodsName: '美的电饭煲',
    status: '启用',
    goodsType: '家电',
    spec: 'IH电磁加热/4L',
    unit: '个',
    barcode: 'MED20240322-001',
    warehouseName: '仓库二',
    locationName: 'C区-02-01',
    currentStock: 156,
    stockAmount: 78000.00,
  },
  {
    index: 23,
    goodsCode: 'HPDH5544',
    goodsName: 'iPhone 15手机壳',
    status: '启用',
    goodsType: '配饰',
    spec: '透明硅胶/全包',
    unit: '个',
    barcode: 'CAS20240323-001',
    warehouseName: '仓库一',
    locationName: 'D区-03-04',
    currentStock: 345,
    stockAmount: 34500.00,
  },
  {
    index: 24,
    goodsCode: 'HPDH4433',
    goodsName: '可口可乐',
    status: '启用',
    goodsType: '食品',
    spec: '330ml/24罐',
    unit: '箱',
    barcode: 'COC20240324-001',
    warehouseName: '仓库二',
    locationName: 'E区-01-02',
    currentStock: 203,
    stockAmount: 30450.00,
  },
  {
    index: 25,
    goodsCode: 'HPDH3322',
    goodsName: '宝洁洗发水',
    status: '启用',
    goodsType: '化妆品',
    spec: '750ml/去屑型',
    unit: '瓶',
    barcode: 'PRO20240325-001',
    warehouseName: '仓库一',
    locationName: 'F区-02-05',
    currentStock: 124,
    stockAmount: 12400.00,
  },
  {
    index: 26,
    goodsCode: 'HPDH2211',
    goodsName: '安踏运动鞋',
    status: '启用',
    goodsType: '鞋类',
    spec: '41码/红色',
    unit: '双',
    barcode: 'ANT20240326-001',
    warehouseName: '仓库二',
    locationName: 'G区-03-01',
    currentStock: 78,
    stockAmount: 23400.00,
  },
  {
    index: 27,
    goodsCode: 'HPDH1100',
    goodsName: '李宁运动裤',
    status: '启用',
    goodsType: '服装',
    spec: 'M码/黑色',
    unit: '件',
    barcode: 'LIN20240327-001',
    warehouseName: '仓库一',
    locationName: 'H区-01-03',
    currentStock: 56,
    stockAmount: 11200.00,
  },
  {
    index: 28,
    goodsCode: 'HPDH9988',
    goodsName: '瑜伽垫',
    status: '启用',
    goodsType: '运动器材',
    spec: '6mm/加厚加宽',
    unit: '个',
    barcode: 'YOG20240328-001',
    warehouseName: '仓库二',
    locationName: 'I区-02-01',
    currentStock: 123,
    stockAmount: 18450.00,
  },
  {
    index: 29,
    goodsCode: 'HPDH8877',
    goodsName: '《三体》三部曲',
    status: '启用',
    goodsType: '书籍',
    spec: '刘慈欣/精装版',
    unit: '套',
    barcode: 'SAN20240329-001',
    warehouseName: '仓库一',
    locationName: 'A区-03-04',
    currentStock: 89,
    stockAmount: 26700.00,
  },
  {
    index: 30,
    goodsCode: 'HPDH7766',
    goodsName: '变形金刚玩具',
    status: '启用',
    goodsType: '玩具',
    spec: '擎天柱/大师级',
    unit: '个',
    barcode: 'TRA20240330-001',
    warehouseName: '仓库二',
    locationName: 'B区-01-01',
    currentStock: 45,
    stockAmount: 45000.00,
  },
];

// 表格数据（根据分页和筛选条件动态更新）
const tableData = ref([]);

// 筛选和分页后的数据
const filteredData = ref([]);

// 分页参数（必须在使用前定义）
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 更新分页数据
const updatePagedData = () => {
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  tableData.value = filteredData.value.slice(start, end).map((item, index) => ({
    ...item,
    index: start + index + 1
  }));
  pagination.total = filteredData.value.length;
};

// 初始化数据
const initData = () => {
  // 复制完整数据以避免直接修改原始数据
  filteredData.value = JSON.parse(JSON.stringify(fullStockData));
  updatePagedData();
};

// 初始化时加载数据
initData();

// 获取类型标签颜色
const getTypeTagType = (type) => {
  const typeMap = {
    '电子产品': 'primary',
    '家电': 'success',
    '服装': 'warning',
    '食品': 'danger',
    '化妆品': 'info',
    '鞋类': 'warning',
    '配饰': 'primary',
    '玩具': 'success',
    '书籍': 'info',
    '运动器材': 'danger',
    '家居用品': 'success',
    '文具': 'warning'
  };
  return typeMap[type] || 'default';
};

// 格式化日期辅助函数
const formatYesterday = () => {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  return yesterday.toLocaleDateString();
};

// 获取当前周数
const getCurrentWeek = () => {
  const date = new Date();
  const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
  const pastDaysOfYear = (date - firstDayOfYear) / 86400000;
  return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7);
};

// 获取当前月份
const getCurrentMonth = () => {
  return new Date().getMonth() + 1;
};

// 获取上个月
const getLastMonth = () => {
  const date = new Date();
  return date.getMonth() === 0 ? 12 : date.getMonth();
};

// 时间筛选逻辑（真实数据筛选）
const handleTime = (type) => {
  activeTime.value = type;
  console.log('时间筛选类型：', type);
  
  // 模拟加载状态
  const loading = ElLoading.service({
    lock: true,
    text: '正在切换时间范围...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  // 模拟数据加载延迟
  setTimeout(() => {
    // 更新统计数据
    updateStatisticsByTime(type);
    
    // 重新应用筛选条件
    applyFilters();
    
    loading.close();
    ElMessage.success(`已切换到${getLabelByTimeType(type)}数据`);
  }, 500);
};

// 根据时间类型获取标签
const getLabelByTimeType = (type) => {
  const labels = {
    today: '今日',
    yesterday: '昨日',
    thisWeek: '本周',
    lastWeek: '上周',
    thisMonth: '本月',
    lastMonth: '上月',
    halfYear: '最近半年',
    oneYear: '最近一年',
    custom: '自定义时间'
  };
  return labels[type] || type;
};

// 应用筛选条件
const applyFilters = () => {
  // 重置到第一页
  pagination.currentPage = 1;
  
  // 从完整数据开始筛选
  filteredData.value = JSON.parse(JSON.stringify(fullStockData));
  
  // 应用各筛选条件
  if (searchForm.goodsName) {
    const keyword = searchForm.goodsName.toLowerCase();
    filteredData.value = filteredData.value.filter(item => 
      item.goodsName.toLowerCase().includes(keyword) || 
      item.goodsCode.toLowerCase().includes(keyword)
    );
  }
  
  if (searchForm.goodsType) {
    filteredData.value = filteredData.value.filter(item => 
      item.goodsType === searchForm.goodsType
    );
  }
  
  if (searchForm.unit) {
    filteredData.value = filteredData.value.filter(item => 
      item.unit === searchForm.unit
    );
  }
  
  if (searchForm.warehouseName) {
    filteredData.value = filteredData.value.filter(item => 
      item.warehouseName === searchForm.warehouseName
    );
  }
  
  if (searchForm.barcode) {
    filteredData.value = filteredData.value.filter(item => 
      item.barcode.includes(searchForm.barcode)
    );
  }
  
  if (!searchForm.showDisabled) {
    filteredData.value = filteredData.value.filter(item => 
      item.status === '启用'
    );
  }
  
  if (!searchForm.showZeroStock) {
    filteredData.value = filteredData.value.filter(item => 
      item.currentStock > 0
    );
  }
  
  // 更新分页数据
  updatePagedData();
};

// 查询逻辑（真实数据筛选）
const handleSearch = () => {
  console.log('查询条件：', searchForm);
  
  // 模拟查询延迟和加载状态
  const loading = ElLoading.service({
    lock: true,
    text: '正在查询数据...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  // 模拟查询延迟
  setTimeout(() => {
    applyFilters();
    loading.close();
    console.log('查询成功，显示结果');
    ElMessage.success(`查询成功，共${pagination.total}条记录`);
  }, 500);
};

// 重置逻辑
const handleReset = () => {
  searchForm.goodsName = '';
  searchForm.goodsType = '';
  searchForm.unit = '';
  searchForm.warehouseName = '';
  searchForm.barcode = '';
  searchForm.showDisabled = false;
  searchForm.showZeroStock = false;
};

// 导出逻辑（模拟真实导出操作）
const handleExport = () => {
  console.log('导出数据');
  ElMessage.info('数据导出中，请稍候...');
  // 模拟导出延迟
  setTimeout(() => {
    ElMessage.success('数据导出成功！');
  }, 1000);
};

// 刷新逻辑（模拟真实刷新操作）
const handleRefresh = () => {
  console.log('刷新页面');
  // 模拟刷新延迟和加载状态
  const loading = ElLoading.service({
    lock: true,
    text: '正在刷新数据...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  // 模拟刷新延迟
  setTimeout(() => {
    loading.close();
    console.log('刷新成功');
    ElMessage.success('数据刷新成功！');
  }, 800);
};

// 出入库流水对话框
const stockFlowDialogVisible = ref(false);
const selectedGoods = ref(null);
const stockFlowData = ref([]);

// 库存分布对话框
const stockDistributionDialogVisible = ref(false);
const stockDistributionData = ref([]);

// 生成模拟的出入库流水数据
const generateStockFlowData = (goods) => {
  const types = ['入库', '出库'];
  const reasons = ['采购入库', '销售出库', '调拨入库', '调拨出库', '退货入库', '退货出库'];
  const flowData = [];
  
  // 生成最近30天的模拟数据
  for (let i = 0; i < 30; i++) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    
    // 每天1-3条记录
    const recordCount = Math.floor(Math.random() * 3) + 1;
    
    for (let j = 0; j < recordCount; j++) {
      const type = types[Math.floor(Math.random() * types.length)];
      const reason = reasons[Math.floor(Math.random() * reasons.length)];
      const quantity = Math.floor(Math.random() * 50) + 1;
      const unitPrice = Math.floor(Math.random() * 1000) + 1000;
      
      flowData.push({
        id: `${i}-${j}`,
        date: date.toLocaleDateString(),
        time: `${Math.floor(Math.random() * 24)}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`,
        type,
        reason,
        quantity: type === '入库' ? quantity : -quantity,
        unitPrice,
        amount: quantity * unitPrice,
        operator: `操作员${Math.floor(Math.random() * 10) + 1}`,
        orderNo: `ORDER${Date.now()}-${i}-${j}`
      });
    }
  }
  
  // 按日期排序
  return flowData.sort((a, b) => {
    const dateA = new Date(`${a.date} ${a.time}`);
    const dateB = new Date(`${b.date} ${b.time}`);
    return dateB - dateA;
  }).slice(0, 50); // 只取最近50条
};

// 生成模拟的库存分布数据
const generateStockDistributionData = (goods) => {
  const warehouses = ['仓库一', '仓库二', '临时仓库'];
  const totalStock = goods.currentStock;
  
  // 随机分配库存到不同仓库（避免在初始化过程中引用自身）
  const distributionData = [];
  let remainingStock = totalStock;
  
  // 先处理前两个仓库
  for (let i = 0; i < warehouses.length - 1; i++) {
    // 每个仓库分配0到剩余库存的随机数量
    const stock = remainingStock > 0 ? Math.floor(Math.random() * remainingStock) : 0;
    remainingStock -= stock;
    
    // 生成库位信息
    const locations = [];
    const locationCount = stock > 0 ? Math.floor(Math.random() * 3) + 1 : 0;
    let locationRemainingStock = stock;
    
    for (let j = 0; j < locationCount; j++) {
      const locationStock = j === locationCount - 1 ? locationRemainingStock : Math.floor(Math.random() * locationRemainingStock) + 1;
      locationRemainingStock -= locationStock;
      
      locations.push({
        name: `${String.fromCharCode(65 + j)}区-${String(Math.floor(Math.random() * 5) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 5) + 1).padStart(2, '0')}`,
        stock: locationStock,
        percentage: ((locationStock / stock) * 100).toFixed(2)
      });
    }
    
    distributionData.push({
      warehouse: warehouses[i],
      stock,
      percentage: totalStock > 0 ? ((stock / totalStock) * 100).toFixed(2) : '0.00',
      locations
    });
  }
  
  // 最后一个仓库分配剩余库存
  if (warehouses.length > 0) {
    const stock = remainingStock;
    
    // 生成库位信息
    const locations = [];
    const locationCount = stock > 0 ? Math.floor(Math.random() * 3) + 1 : 0;
    let locationRemainingStock = stock;
    
    for (let j = 0; j < locationCount; j++) {
      const locationStock = j === locationCount - 1 ? locationRemainingStock : Math.floor(Math.random() * locationRemainingStock) + 1;
      locationRemainingStock -= locationStock;
      
      locations.push({
        name: `${String.fromCharCode(65 + j)}区-${String(Math.floor(Math.random() * 5) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 5) + 1).padStart(2, '0')}`,
        stock: locationStock,
        percentage: ((locationStock / stock) * 100).toFixed(2)
      });
    }
    
    distributionData.push({
      warehouse: warehouses[warehouses.length - 1],
      stock,
      percentage: totalStock > 0 ? ((stock / totalStock) * 100).toFixed(2) : '0.00',
      locations
    });
  }
  
  // 只保留有库存的仓库
  return distributionData.filter(item => item.stock > 0);
};

// 出入库流水逻辑
const handleStockFlow = (row) => {
  console.log('出入库流水：', row);
  selectedGoods.value = row;
  stockFlowData.value = generateStockFlowData(row);
  stockFlowDialogVisible.value = true;
};

// 库存分布逻辑
const handleStockDistribution = (row) => {
  console.log('库存分布：', row);
  selectedGoods.value = row;
  stockDistributionData.value = generateStockDistributionData(row);
  stockDistributionDialogVisible.value = true;
};

// 分页逻辑（真实分页操作）
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  console.log('每页条数变更：', val);
  // 更新分页数据
  updatePagedData();
  
  // 模拟加载状态
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载数据...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  // 模拟加载延迟
  setTimeout(() => {
    loading.close();
  }, 300);
};

const handleCurrentChange = (val) => {
  pagination.currentPage = val;
  console.log('当前页码变更：', val);
  // 更新分页数据
  updatePagedData();
  
  // 模拟加载状态
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载数据...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  // 模拟加载延迟
  setTimeout(() => {
    loading.close();
  }, 300);
};
</script>

<style scoped>
.inventory-page {
  padding: 16px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  position: relative;
  z-index: 1;
  padding: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #fff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 16px;
}

.stat-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 40px;
  color: rgba(255, 255, 255, 0.2);
}

.bg-gradient-primary {
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
}

.bg-gradient-success {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
}

.bg-gradient-warning {
  background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
}

.text-orange {
  color: #e6a23c;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.table-title {
  font-size: 16px;
  font-weight: 500;
  color: #606266;
}

.data-count {
  font-size: 14px;
  color: #909399;
}

.goods-name {
  color: #409EFF;
  cursor: pointer;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.goods-name:hover {
  text-decoration: underline;
}

.stock-low {
  color: #e6a23c;
  font-weight: 500;
}

.stock-zero {
  color: #f56c6c;
  font-weight: 500;
}

.amount {
  color: #67c23a;
  font-weight: 500;
}

.hover-row {
  background-color: #f5f7fa !important;
}

.el-table {
  margin-bottom: 16px;
}

.el-form-item {
  margin-bottom: 20px;
}

/* 出入库流水对话框样式 */
.flow-dialog-content {
  max-height: 60vh;
  overflow-y: auto;
}

.flow-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-item .label {
  font-weight: 500;
  margin-right: 8px;
  color: #606266;
}

.summary-item .value {
  color: #303133;
}

.stock-value {
  font-weight: 600;
  color: #409EFF;
}

.text-green {
  color: #67c23a;
}

.text-red {
  color: #f56c6c;
}

/* 库存分布对话框样式 */
.distribution-dialog-content {
  max-height: 70vh;
  overflow-y: auto;
}

.distribution-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.warehouse-distribution {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.warehouse-card {
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fff;
}

.warehouse-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.warehouse-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.warehouse-stock {
  font-weight: 600;
  color: #409EFF;
}

.warehouse-percentage {
  margin-bottom: 16px;
}

.locations-title {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #606266;
}

.location-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.location-item {
  padding: 8px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.location-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.location-name {
  color: #606266;
}

.location-stock {
  font-weight: 500;
  color: #303133;
}

.location-percentage {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .el-form--inline .el-form-item {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }
  
  .el-form-item__label {
    width: 100%;
    margin-right: 0;
    margin-bottom: 8px;
  }
  
  .flex {
    flex-direction: column;
  }
  
  .flex > * {
    margin-bottom: 10px;
  }
  
  .flow-summary,
  .distribution-summary {
    flex-direction: column;
    gap: 10px;
  }
  
  .summary-item {
    width: 100%;
  }
  
  .warehouse-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .location-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>